package com.lzc.tlmail.tlmailsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lzc.common.to.es.SkuEsModel;
import com.lzc.common.utils.R;
import com.lzc.tlmail.tlmailsearch.config.ElasticsearchConfig;
import com.lzc.tlmail.tlmailsearch.constant.EsConstant;
import com.lzc.tlmail.tlmailsearch.feign.ProductFeignService;
import com.lzc.tlmail.tlmailsearch.service.MallSearchService;
import com.lzc.tlmail.tlmailsearch.vo.AttrrespVo;
import com.lzc.tlmail.tlmailsearch.vo.BrandVo;
import com.lzc.tlmail.tlmailsearch.vo.SearchParam;
import com.lzc.tlmail.tlmailsearch.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lzc
 * @create 2020-09-30 19:48
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Resource
    private RestHighLevelClient client;

    @Resource
    private ProductFeignService productFeignService;

    /**
     * 根据检索条件返回检索结果使用Es
     *
     * @param searchParam
     * @return
     */
    @Override
    public SearchResult search(SearchParam searchParam) {
        //1 动态构建出查询需要的DSL语句
        SearchResult result = null;
        //准备检索请求
        SearchRequest searchRequest = buildSearchRequrest(searchParam);
        try {
            //执行检索请求
            SearchResponse response = client.search(searchRequest, ElasticsearchConfig.COMMON_OPTIONS);
            //分析响应数据分装成指定需要的格式
            result = buildSearchResult(response, searchParam);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 构建结果数据
     *
     * @param response
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response, SearchParam searchParam) {
        SearchResult result = new SearchResult();
        //获取所有记录
        SearchHits hits = response.getHits();
        //获取hits里面实际的hits
        SearchHit[] hits1 = hits.getHits();
        List<SkuEsModel> skuEsModelList = new ArrayList<>();
        if (hits1 != null && hits1.length > 0) {
            for (SearchHit hit : hits1) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (!StringUtils.isEmpty(searchParam.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(string);
                }

                skuEsModelList.add(skuEsModel);
            }
        }
        //1返回所有查询到的商品
        result.setSkuEsModels(skuEsModelList);
        //2返回当前所有商品涉及到的所有属性信息
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attrs_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attrs_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //得到属性id
            long attrId = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);

            //得到属性名字
            String attr_name_agg = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attr_name_agg);
            //得到所有属性值
            List<String> attr_values = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                String keyAsString = ((Terms.Bucket) item).getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
            attrVo.setAttrValue(attr_values);
            attrVos.add(attrVo);
        }

        result.setAttrs(attrVos);
        //3返回当前商品涉及到的品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //得到品牌id
            long l = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(l);
            //品牌图片
            String brand_img_agg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brand_img_agg);
            //名字
            String brand_name_agg = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brand_name_agg);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);
        //4返回当前商品涉及到的分类信息

        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            //得到分类id
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            catalogVo.setCatalogId(Long.parseLong(bucket.getKeyAsString()));

            //得到分类名
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalog_name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalog_name);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);
        //5返回当前商品涉及到的分页信息
        //总记录数
        long total = hits.getTotalHits().value;
        //总页吗
        int totalPages = (int) total % EsConstant.PRODUCT_PAGESIZE == 0 ? (int) total / EsConstant.PRODUCT_PAGESIZE : (int) (total / EsConstant.PRODUCT_PAGESIZE + 1);
        //当前页码
        result.setPageNum(searchParam.getPageNum());
        result.setTotalPages(totalPages);
        result.setTotal(total);
        List<Integer> navs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            navs.add(i);
        }
        result.setNavs(navs);
        List<Long> attrIds = result.getAttrIds();
        //构建属性导航
        if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0) {
            List<SearchResult.NavNo> navNos = searchParam.getAttrs().stream().map(attr -> {
                SearchResult.NavNo navNo = new SearchResult.NavNo();
                String[] s = attr.split("_");
                attrIds.add(Long.parseLong(s[0]));
                R r = productFeignService.attrinfo(Long.parseLong(s[0]));
                if (r .getCode()==0) {
                    AttrrespVo attr1 = r.getData("attr", new TypeReference<AttrrespVo>(){});
                    navNo.setNavName(attr1.getAttrName());
                } else {
                    navNo.setNavName(s[0]);
                }
                navNo.setNavValue(s[1]);
                //取消属性条件 就是把地址栏的条件置空
                String queryString = searchParam.getQueryString();
//                String decode = null;
//                try {
//                    decode = URLEncoder.encode(attr, "UTF-8");
//                    decode=decode.replace("+","%20");
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
                String name ="";
                if(queryString.indexOf("&")!=-1){
                    name="&attrs=";
                }else {
                    name="attrs=";
                }
                String replace = getQueryLink(name,queryString,attr);
                navNo.setLink("http://search.tlmail.com/list.html?"+replace);
                return navNo;
            }).collect(Collectors.toList());
            result.setNavs1(navNos);
        }
        result.setAttrIds(attrIds);
        //添加品牌面包屑
        if(searchParam.getBrandId()!=null&&searchParam.getBrandId().size()>0){
            List<SearchResult.NavNo> navs1 = result.getNavs1();
            SearchResult.NavNo navNo = new SearchResult.NavNo();
            navNo.setNavName("品牌");
            //TODO 调用远程商品服务得到品牌
            List<BrandVo> brandVos1 = productFeignService.getBrandsByBrandsId(searchParam.getBrandId());
            StringBuffer stringBuffer = new StringBuffer();
            String queryString = searchParam.getQueryString();
            String name ="";
            if(queryString.indexOf("&")!=-1){
                name="&brandId=";
            }else {
                name="brandId=";
            }
            String replace =null;
            for (BrandVo brandVo : brandVos1) {
                stringBuffer.append(brandVo.getBrandName());

                replace=getQueryLink(name,queryString,brandVo.getBrandId().toString());
            }
            navNo.setNavValue(stringBuffer.toString());
            navNo.setLink("http://search.tlmail.com/list.html?"+replace);
            navs1.add(navNo);
        }
        return result;
    }

    /**
     * 获取返回链接
     * @return
     */
    public String getQueryLink(String name,String queryString,String type){
        String decode = null;
        try {
            decode = URLEncoder.encode(type, "UTF-8");
            decode=decode.replace("+","%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String replace = queryString.replace(name + decode, "");
        return replace;
    }

    /**
     * 准备检索请求
     * //#模糊匹配，过滤(按照属性，分类，品牌，价格区间，库存),排序,分页，高亮，聚合分析
     * //#如果是嵌入式的属性 查询 聚合都应该使用嵌入式方式
     *
     * @return
     */
    private SearchRequest buildSearchRequrest(SearchParam searchParam) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();//构建DSL语句
        /**
         * 模糊匹配，过滤(按照属性，分类，品牌，价格区间，库存),
         */
        //1构建bool
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //1.1 must
        if (!StringUtils.isEmpty(searchParam.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword()));
        }
        //1.2bool filter 按照三级分类
        if (searchParam.getCatalog3Id() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", searchParam.getCatalog3Id()));
        }
        //1.2 bool filter 按照品牌的id
        if (searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0) {
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
        }
        //1.2bool filter 嵌入式 按属性来
        if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0) {

            for (String attrStr : searchParam.getAttrs()) {
                BoolQueryBuilder nestedboolQuery = QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
                String attrId = s[0];//检索的属性id

                String[] attrValues = s[1].split(":");//这个属性的检索用的值
                nestedboolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedboolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedboolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQuery);
            }

        }
        //1.2bool filter 按照是否有库存
        if (searchParam.getHasStock() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", searchParam.getHasStock() == 1));
        }
        //1.2 bool filter 按照价格区间
        if (!StringUtils.isEmpty(searchParam.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = searchParam.getSkuPrice().split("_");
            if (s.length == 2) {
                rangeQuery.gte(s[0]).lte(s[1]);
            } else if (s.length == 1) {
                if (searchParam.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(s[0]);
                }
                if (searchParam.getSkuPrice().endsWith("_")) {
                    rangeQuery.lte(s[0]);
                }
            }

            boolQueryBuilder.filter(rangeQuery);

        }
        sourceBuilder.query(boolQueryBuilder);
        /**
         * 排序,分页，高亮，
         */
        //2.1排序
        if (!StringUtils.isEmpty(searchParam.getSort())) {
            String sort = searchParam.getSort();
            String[] strings = sort.split("_");
            SortOrder order = strings[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(strings[0], order);
        }
        //2.2分页
        sourceBuilder.from((searchParam.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        //2.3高亮
        if (!StringUtils.isEmpty(searchParam.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }

        /**
         * 聚合分析
         */
        //1品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        //品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);
        //2分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);
        //3属性聚合
        NestedAggregationBuilder attrs = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(10);
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attrs.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(attrs);
        String s = sourceBuilder.toString();
        System.out.println("dsl构建的语句" + s);
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }
}
